package com.example.springboottestgit.service;

import com.alibaba.fastjson.JSONObject;
import com.example.springboottestgit.bean.BusinessException;
import com.example.springboottestgit.bean.InviteTenderContentQaRecord;
import com.example.springboottestgit.bean.SubmitTenderContentQaRecord;
import com.example.springboottestgit.bean.vo.InputVO;
import com.example.springboottestgit.bean.vo.OutputVO;
import com.example.springboottestgit.bean.vo.TechnologyVO;
import com.example.springboottestgit.dao.InviteTenderContentQaRecordMapper;
import com.example.springboottestgit.dao.SubmitTenderContentQaRecordMapper;
import com.example.springboottestgit.dao.SubmitTenderFileUploadRecordMapper;
import com.example.springboottestgit.enums.ExceptionCodeEnum;
import com.example.springboottestgit.utils.FileUtil;
import com.example.springboottestgit.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: ZZZ
 */
@Slf4j
@Service
public class ModelServer {


    @Value("${tender.technology.query.url}")
    private String tenderTechnologyQueryUrl;


    @Value("${tender.unite.url}")
    private String tenderUniteUrl;

    @Value("${law.check.switch}")
    private Boolean lawCheckSwitch;

    @Value("${law.check.list}")
    private List<String> lawCheckList;

    @Value("${authorization.switch}")
    private Boolean authorizationSwitch;

    @Value("${authorization.list}")
    private List<String> authorizationList;


    @Value("${es.negative.list.query.size}")
    private Integer negativeListQuerySize;

    @Value("${es.common.query.size}")
    private Integer commonQuerySize;

    @Value("${es.technology.query.size}")
    private Integer technologyQuerySize;

    @Value("${es.business.query.document.length.switch}")
    private boolean businessDocumentLengthSwitch;

    @Value("${es.business.query.document.max.length}")
    private Integer businessDocumentMaxLength;


    @Autowired
    private ElasticSearchClientServer es;


    @Autowired
    private InviteTenderContentQaRecordMapper inviteTenderContentQaRecordMapper;
    @Autowired
    private SubmitTenderContentQaRecordMapper submitTenderContentQaRecordMapper;
    @Autowired
    private SubmitTenderFileUploadRecordMapper submitTenderFileUploadRecordMapper;

    //@Async("myAsync")
    public void inviteTenderContentQa(InviteTenderContentQaRecord insert, String questionName, String filePath) {
        //测试
        //filePath="/home/linweibin/liujian/project/policy-tender/data/物业服务招标文件-7bfd3e9fd23a446dafe5cf11307a41a8";
        try {
            LocalDateTime s = LocalDateTime.now();
            log.info("========{}==========", questionName);
//            String indexId = "z" + insert.getInviteTenderFileId();
//            String result = HttpUtils.tenderQuestionRetrieval(questionName, indexId, filePath, tenderRetrievalUrl);
//            insert.setResult(result);
//            insert.setStatus(1);
//            inviteTenderContentQaRecordMapper.insert(insert);
            LocalDateTime e = LocalDateTime.now();
            Duration between = Duration.between(s, e);
            log.info("招标文件:{}  问答耗时 {} 秒", questionName, between.getSeconds());
        } catch (Exception e) {
            //失败
            insert.setStatus(2);
            inviteTenderContentQaRecordMapper.insert(insert);
            throw new BusinessException("001001", "招标文件解析失败");
        }

    }


    @Async("myAsync")
    public void submitTenderContentQa(SubmitTenderContentQaRecord insert, String inviteSearchContent, String submitSearchContent, String inviteTenderTxtPath, String submitTenderTxtPath, String inviteTenderIndexId, String submitTenderIndexId) throws InterruptedException {
        InviteTenderContentQaRecord inviteTenderContentQaRecord = new InviteTenderContentQaRecord();
        int questionType = insert.getQuestionType();
        try {

            //questionType 1:招标+投标问题 需要匹配  2：投标问题 不需要匹配
            LocalDateTime startTime = LocalDateTime.now();
            //招标问题
            String inviteQuestionName = insert.getInviteQuestionName();
            //投标问题
            String submitQuestionName = insert.getSubmitQuestionName();
            inviteTenderContentQaRecord.setQuestionType(questionType);
            inviteTenderContentQaRecord.setInspectItemType(insert.getInspectItemType());

            log.info("=====================招投标 问题检索======================");
            //4 负面清单
            if (questionType == 4) {
                inviteTenderContentQaRecord.setBsn(insert.getBsn());
                //inviteTenderContentQaRecord.setInviteTenderFileId(insert.getInviteTenderFileId());
                inviteTenderContentQaRecord.setQuestionId(insert.getQuestionId());
                inviteTenderContentQaRecord.setQuestionName(inviteQuestionName);
                inviteTenderContentQaRecord.setInspectItem("政府采购负面清单检查");
                String fragment = es.queryContent(inviteTenderIndexId, inviteSearchContent, negativeListQuerySize);
                if (businessDocumentLengthSwitch) {
                    fragment = fragment.length() > businessDocumentMaxLength ? fragment.substring(0, businessDocumentMaxLength) : fragment;
                }
                inviteTenderContentQaRecord.setFragment(fragment);
                inviteTenderContentQaRecordMapper.insert(inviteTenderContentQaRecord);

                String policyBasis = inviteQuestionName;
                //String inviteTenderResult = HttpUtils.negativeListCheck(policyBasis, fragment, negativeListCheckUrl);
                String inviteTenderResult = HttpUtils.tenderUnite(fragment, policyBasis, "complian", tenderUniteUrl);
                //OutputVO outputVO = JSONObject.parseObject(inviteTenderResult, OutputVO.class);
                //String result = contentFilter(outputVO.getResult());
                //inviteTenderContentQaRecord.setResult(result);
                //inviteTenderContentQaRecord.setResult(inviteQuestionName);
                inviteTenderContentQaRecord.setResult(insert.getInspectItem());
                inviteTenderContentQaRecord.setMateMark(getMateResult(inviteTenderResult));
                inviteTenderContentQaRecord.setMateResult(inviteTenderResult);
                inviteTenderContentQaRecord.setStatus(1);
                inviteTenderContentQaRecord.setExeStatus(1);
                // 记录片段
                //txtWriter(inviteTenderTxtPath, fragment, insert.getInspectItem());
                inviteTenderContentQaRecordMapper.updateById(inviteTenderContentQaRecord);
                return;
            }
            //1 通用问题 3 资格文件
            if (questionType == 1 || questionType == 3) {
                //InviteTenderContentQaRecord inviteTenderContentQaRecord = inviteTenderContentQaRecordMapper.queryInviteTender(insert.getBsn(), insert.getQuestionId());
                inviteTenderContentQaRecord.setBsn(insert.getBsn());
                //inviteTenderContentQaRecord.setInviteTenderFileId(insert.getInviteTenderFileId());
                inviteTenderContentQaRecord.setQuestionId(insert.getQuestionId());
                inviteTenderContentQaRecord.setQuestionName(inviteQuestionName);
                inviteTenderContentQaRecord.setInspectItem(insert.getInspectItem());
                String fragment = es.queryContent(inviteTenderIndexId, inviteSearchContent, commonQuerySize);
                if (businessDocumentLengthSwitch) {
                    fragment = fragment.length() > businessDocumentMaxLength ? fragment.substring(0, businessDocumentMaxLength) : fragment;
                }
                inviteTenderContentQaRecord.setFragment(fragment);
                inviteTenderContentQaRecordMapper.insert(inviteTenderContentQaRecord);

                //String inviteTenderResult = HttpUtils.tenderQuestionRetrieval(inviteQuestionName, fragment, tenderRetrievalUrl);
                String inviteTenderResult = HttpUtils.tenderUnite(fragment, inviteQuestionName, "tender", tenderUniteUrl);
                //OutputVO outputVO = JSONObject.parseObject(inviteTenderResult, OutputVO.class);
                //String result = contentFilter(outputVO.getResult());
                inviteTenderContentQaRecord.setResult(inviteTenderResult);
                inviteTenderContentQaRecord.setStatus(1);
                inviteTenderContentQaRecord.setExeStatus(1);
                // 记录片段
                txtWriter(inviteTenderTxtPath, fragment, inviteQuestionName);
                inviteTenderContentQaRecordMapper.updateById(inviteTenderContentQaRecord);

                if (inviteTenderContentQaRecord.getResult().contains("无相关")) {
                    return;
                }
                if (questionType == 3) {
                    if (inviteTenderContentQaRecord.getResult().contains("没有明确") || inviteTenderContentQaRecord.getResult().contains("无法确认") || inviteTenderContentQaRecord.getResult().contains("没有要求")) {
                        return;
                    }
                }

                insert.setInviteTenderResult(inviteTenderContentQaRecord.getResult());
            }

            String fragment = es.queryContent(submitTenderIndexId, submitSearchContent, commonQuerySize);
            if (businessDocumentLengthSwitch) {
                fragment = fragment.length() > businessDocumentMaxLength ? fragment.substring(0, businessDocumentMaxLength) : fragment;
            }
            insert.setFragment(fragment);
            submitTenderContentQaRecordMapper.insert(insert);

            //String submitTenderResult = HttpUtils.tenderQuestionRetrieval(submitQuestionName, fragment, tenderRetrievalUrl);
            String submitTenderResult = HttpUtils.tenderUnite(fragment, submitQuestionName, "tender", tenderUniteUrl);
            //OutputVO outputVO = JSONObject.parseObject(submitTenderResult, OutputVO.class);
            //String result = contentFilter(outputVO.getResult());

            insert.setResult(submitTenderResult);
            // 记录片段
            txtWriter(submitTenderTxtPath, fragment, submitQuestionName);

            submitTenderContentQaRecordMapper.updateById(insert);


            LocalDateTime middleTime = LocalDateTime.now();
            Duration between1 = Duration.between(startTime, middleTime);
            log.info("投标文件:{}  问题检索耗时 {} 秒", submitQuestionName, between1.getSeconds());


            if (questionType == 1) {
                log.info("========招投标 结果匹配==========");
                //String tenderMateResult = HttpUtils.tenderMateResult(insert.getInviteTenderResult(), insert.getResult(), tenderMateUrl);
                String tenderMateResult = HttpUtils.tenderUnite(insert.getInviteTenderResult(), insert.getResult(), "infer", tenderUniteUrl);
                //OutputVO mateOutput = JSONObject.parseObject(tenderMateResult, OutputVO.class);
                //String mateResult = mateOutput.getResult();
                insert.setMateMark(getMateResult(tenderMateResult));
                insert.setMateResult(tenderMateResult);
                //submitTenderContentQaRecordMapper.updateById(insert);
                //法律法规合法性校验
                // 前面招标文件已经做了法律法规校验，这里就不在校验了（20250923）
                /*
                if ("符合".equals(insert.getMateMark()) && lawCheckSwitch && lawCheckList.contains(insert.getInspectItem())) {
                    log.info("========招投标 法律法规校验==========");
                    //String lawCheckResult = HttpUtils.lawCheck(result, tenderLawUrl);
                    String lawCheckResult = HttpUtils.tenderUnite(submitTenderResult, null, "law", tenderUniteUrl);
                    //OutputVO lawOutput = JSONObject.parseObject(lawCheckResult, OutputVO.class);
                    //String checkResult = lawOutput.getResult();
                    insert.setMateMark(getMateResult(lawCheckResult));
                    insert.setMateResult(lawCheckResult);
                }
                */

            } else {
                String mateMark = insert.getResult().contains("无相关") ? "不符合" : "符合";
                insert.setMateMark(mateMark);
                insert.setMateResult(insert.getResult());

                //授权委托书校验 （前提是要检索出内容，即符合）
                if ("符合".equals(mateMark) && authorizationSwitch && authorizationList.contains(insert.getInspectItem())) {
                    log.info("========招投标 授权委托书校验==========");
                    //submitTenderContentQaRecordMapper.submitTenderResult(insert.getSubmitTenderFileId(), insert.getInspectItem());
                    //String projectNo = "项目编号:\n" + submitTenderContentQaRecordMapper.submitTenderResult(insert.getSubmitTenderFileId(), "项目编号");
                    //String companyName = "投标公司名称:\n" + submitTenderContentQaRecordMapper.submitTenderResult(insert.getSubmitTenderFileId(), "投标公司名称");
                    //String legalRepresentative = "法定代表人:\n" + submitTenderContentQaRecordMapper.submitTenderResult(insert.getSubmitTenderFileId(), "法定代表人");
                    //String delegator = "授权委托人:\n" + submitTenderContentQaRecordMapper.submitTenderResult(insert.getSubmitTenderFileId(), "授权委托人");

                    //String projectNo = submitTenderContentQaRecordMapper.submitTenderResult(insert.getSubmitTenderFileId(), "项目编号");
                    String name = submitTenderContentQaRecordMapper.submitTenderResult(insert.getBsn(), "投标人名称");
                    //String legalRepresentative = submitTenderContentQaRecordMapper.submitTenderResult(insert.getSubmitTenderFileId(), "法定代表人");
                    // String delegator = submitTenderContentQaRecordMapper.submitTenderResult(insert.getSubmitTenderFileId(), "授权委托人");


                    //String proveCheckResult = HttpUtils.proveCheck(insert.getResult(), name, tenderProveUrl);
                    String proveCheckResult = HttpUtils.tenderUnite(insert.getResult(), name, "prove", tenderUniteUrl);
                    //OutputVO proveOutput = JSONObject.parseObject(proveCheckResult, OutputVO.class);
                    //String checkResult = proveOutput.getResult();
                    insert.setMateMark(getMateResult(proveCheckResult));
                    insert.setMateResult(proveCheckResult);
                }

            }
            LocalDateTime endTime = LocalDateTime.now();
            Duration between2 = Duration.between(middleTime, endTime);
            insert.setStatus(1);
            insert.setExeStatus(1);
            submitTenderContentQaRecordMapper.updateById(insert);
            log.info("招投标文件:{}  耗时 {} 秒\n\n", submitQuestionName, between2.getSeconds());
        } catch (Exception e) {
            log.error("===招投标 问题检索失败===");
            if (inviteTenderContentQaRecord.getId() != null) {
                inviteTenderContentQaRecord.setExeStatus(1);
                inviteTenderContentQaRecord.setStatus(2);
                inviteTenderContentQaRecordMapper.updateById(inviteTenderContentQaRecord);
            }
            if (insert.getId() != null) {
                insert.setExeStatus(1);
                insert.setStatus(2);
                submitTenderContentQaRecordMapper.updateById(insert);
            }


        }

    }

    @Async("myAsync")
    public void lawCheck(String inviteTenderContent, String bsn) {
        InviteTenderContentQaRecord inviteTenderContentQaRecord = new InviteTenderContentQaRecord();
        try {
            inviteTenderContentQaRecord.setInspectItemType(5);
            inviteTenderContentQaRecord.setResult(inviteTenderContent);
            //inviteTenderContentQaRecord.setQuestionType(questionType);
            //InviteTenderContentQaRecord inviteTenderContentQaRecord = inviteTenderContentQaRecordMapper.queryInviteTender(insert.getBsn(), insert.getQuestionId());
            inviteTenderContentQaRecord.setBsn(bsn);
            //inviteTenderContentQaRecord.setInviteTenderFileId(insert.getInviteTenderFileId());
            //inviteTenderContentQaRecord.setQuestionId(insert.getQuestionId());
            //inviteTenderContentQaRecord.setQuestionName(inviteQuestionName);
            inviteTenderContentQaRecord.setInspectItem("法律法规合法性检查");
            inviteTenderContentQaRecordMapper.insert(inviteTenderContentQaRecord);

            String lawCheckResult = HttpUtils.tenderUnite(inviteTenderContent, null, "law", tenderUniteUrl);
            inviteTenderContentQaRecord.setMateMark(getMateResult(lawCheckResult));
            inviteTenderContentQaRecord.setMateResult(lawCheckResult);
            inviteTenderContentQaRecord.setStatus(1);
            inviteTenderContentQaRecord.setExeStatus(1);
            inviteTenderContentQaRecordMapper.updateById(inviteTenderContentQaRecord);


        } catch (Exception e) {
            log.error("===法律法规 接口调用异常===");
            if (inviteTenderContentQaRecord.getId() != null) {
                inviteTenderContentQaRecord.setExeStatus(1);
                inviteTenderContentQaRecord.setStatus(2);
                inviteTenderContentQaRecordMapper.updateById(inviteTenderContentQaRecord);
            }
        }

    }

    public String textContent(String filePath) throws IOException {
        FileReader reader = new FileReader(filePath);
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        bufferedReader.close();
        return stringBuilder.toString();
    }


    @Async("myAsync")
    public void tenderFamiliarityMate(InviteTenderContentQaRecord insert, String inviteTechnology, String submitTechnology) {
        try {
            String result = HttpUtils.tenderUnite(inviteTechnology, submitTechnology, "tech", tenderUniteUrl);
            insert.setMateMark(getMateResult(result));
            insert.setMateResult(result);
            insert.setStatus(1);
            insert.setExeStatus(1);
            inviteTenderContentQaRecordMapper.updateById(insert);
        } catch (Exception e) {
            if (insert.getId() != null) {
                insert.setExeStatus(1);
                insert.setStatus(2);
                inviteTenderContentQaRecordMapper.updateById(insert);
            }
        }

    }


    public void technologyAndServicesMethod2(String bsn, String submitTenderTxtPath, String inviteTenderTxtPath) throws IOException {

        //submitTenderTxtPath = "/home/linweibin/liujian/project/policy-tender/data/08a4f70d270d4374be268e6d3ef29d8f-投标/技术文件-拆分后.txt";
        //inviteTenderTxtPath = "C:\\Users\\user\\Desktop\\测试2\\3784667615314ef9a51c3aa5642c1528-招标\\技术文件-拆分后.txt";
        submitTenderTxtPath = submitTenderTxtPath + "/技术文件-拆分后.txt";
        inviteTenderTxtPath = inviteTenderTxtPath + "/技术文件-拆分后.txt";
        LocalDateTime startTime = LocalDateTime.now();

        //招投标技术要求 查询
        String technologyContent = getTechnologyContent(inviteTenderTxtPath);
        String[] technologyList = technologyContent.split("\\*\\*\\*\\*\\*");
        List<TechnologyVO> list = new ArrayList<>();
        for (String technology : technologyList) {
            TechnologyVO vo = new TechnologyVO();
            if (technology.replace(" ", "").length() > 10) {
                vo.setInviteTender(technology);
                list.add(vo);
            }
        }
        InputVO inputVO = new InputVO();
        inputVO.setFile_path(submitTenderTxtPath);
        inputVO.setTechnologyList(list);

        String param = JSONObject.toJSONString(inputVO);

        txtWriter(submitTenderTxtPath, param, "招投标技术要求查询的接口输入参数");

        String result = HttpUtils.submitTenderTechnologyQuery(param, tenderTechnologyQueryUrl);

        txtWriter(submitTenderTxtPath, result, "招投标技术要求查询的接口返回结果");

        OutputVO outputVO = JSONObject.parseObject(result, OutputVO.class);
        List<TechnologyVO> queryList = outputVO.getTenderContent();
        if (queryList == null) {
            log.error("投标技术要求查询 接口调用失败");
            throw new BusinessException(ExceptionCodeEnum.INTERFACE_CALL_FAIL.code, "投标技术要求查询 接口调用失败");
        }
        //招投标技术要求 相识度匹配
        for (TechnologyVO technologyVO : queryList) {
            //String inviteTender = technologyVO.getInviteTender().replace("#####", "*****");
            String inviteTender = technologyVO.getInviteTender();
            String[] split1 = inviteTender.split("\\*\\*\\*\\*\\*");
            for (String s1 : split1) {
                if (s1.replace(" ", "").length() > 10) {
                    if (s1.contains("$$$$$")) {
                        String[] split2 = s1.split("\\$\\$\\$\\$\\$");
                        for (String s2 : split2) {
                            if (s2.length() > 5) {
                                //tenderFamiliarityMate(bsn, s2, technologyVO.getSubmitTender(), 1);
                            }
                        }
                    } else {
                        //tenderFamiliarityMate(bsn, s1, technologyVO.getSubmitTender(), 0);
                    }
                }
            }
        }
        LocalDateTime endTime = LocalDateTime.now();
        Duration between2 = Duration.between(startTime, endTime);
        log.info("招投标技术要求 相识度匹配:  耗时  {}  秒", between2.getSeconds());
    }


    public String getTechnologyContent(String path) throws IOException {
        FileReader reader = new FileReader(path);
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        bufferedReader.close();
        return stringBuilder.toString();
    }


    public String getMateResult(String content) {
        content = content.length() > 10 ? content.substring(0, 8) : content;
        String mateMark = "不符合";
        if (content.contains("符合")) {
            mateMark = "符合";
            if (content.contains("不符合")) {
                mateMark = "不符合";
            }
        }
        return mateMark;
    }


    public String contentFilter(String content) {
        /**
         content = content.replace("根据提供的知识文本片段", "")
         .replace("根据知识文本片段中的信息", "")
         .replace("根据提供的知识文本", "");
         if (content.startsWith(",") || content.startsWith("，")) {
         content = content.substring(1);
         }
         **/
        return content;
    }

    public void txtWriter(String filePath, String fileContent, String newFileName) {
        File file = new File(filePath);
        String fileName = file.getName();
        newFileName = newFileName + "-" + fileContent.length() + ".txt";
        filePath = filePath.replace(fileName, newFileName);

        FileUtil.txtWriter(filePath, fileContent);
    }


}
